package com.peanut.baby.mvp.main;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.peanut.baby.AppConfig;
import com.peanut.baby.BuildConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.comm.DingyueDialog;
import com.peanut.baby.config.ConfigParamsManager;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.model.PTag;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.baby.model.User;
import com.peanut.baby.mvp.about.AboutActivity;
import com.peanut.baby.mvp.about.BusinessActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.dingyue.DingyueActivity;
import com.peanut.baby.mvp.feedback.FeedbackActivity;
import com.peanut.baby.mvp.follow.FollowFansActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.mycontent.MyContentActivity;
import com.peanut.baby.mvp.mydata.MyDataActivity;
import com.peanut.baby.mvp.point.PointRecordActivity;
import com.peanut.baby.mvp.profileedit.ProfileEditActivity;
import com.peanut.baby.mvp.subscribe.TagSubscribeActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.util.ColorUtils;
import com.peanut.baby.util.PrefUtil;
import com.peanut.baby.util.ShareUtil;
import com.peanut.baby.widget.TopDrawableTextView;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.util.SysUtil;
import com.peanut.devlibrary.util.TimeUtil;
import com.tencent.mars.xlog.Log;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by anonymouslystudio on 2017/7/11.
 */

public class ProfileFragment extends BaseHomeFragment implements View.OnClickListener,
        ProfileFragmentContract.View {
    private static final String TAG = "ProfileFragment";
    @BindView(R.id.profile_avatar)
    CircleImageView avatar;
    Unbinder unbinder;
    @BindView(R.id.profile_nick)
    TextView profileNick;
    @BindView(R.id.profile_sign)
    TextView profileSign;
    @BindView(R.id.profile_tags)
    TextView profileTags;

    @BindView(R.id.profile_about)
    TextView about;
    @BindView(R.id.profile_feedback)
    TextView feedback;
    @BindView(R.id.profile_policy)
    LinearLayout policy;
    @BindView(R.id.profile_business)
    LinearLayout business;
    @BindView(R.id.profile_fans)
    LinearLayout fansContainer;
    @BindView(R.id.profile_follow)
    LinearLayout followContainer;
    @BindView(R.id.profile_point)
    LinearLayout point;
    @BindView(R.id.profile_contact)
    LinearLayout contact;
    @BindView(R.id.profile_share)
    TextView share;
    @BindView(R.id.profile_point_value)
    TextView pointValue;
    @BindView(R.id.profile_fans_value)
    TextView fansValue;
    @BindView(R.id.profile_follow_value)
    TextView followValue;
    @BindView(R.id.profile_company_value)
    TextView companyValue;
    @BindView(R.id.profile_data)
    TopDrawableTextView data;
    @BindView(R.id.profile_moments)
    TopDrawableTextView moments;
    @BindView(R.id.profile_dingyue)
    TopDrawableTextView dingyue;
    @BindView(R.id.profile_wiki)
    TopDrawableTextView wiki;
    @BindView(R.id.profile_contact_value)
    TextView contactValue;
    @BindView(R.id.profile_settings)
    TextView settings;
    @BindView(R.id.profile_partner)
    LinearLayout profilePartner;
    @BindView(R.id.profile_partner_new)
    TextView profilePartnerNew;

    private ProfileFragmentPresenter presenter;

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_profile, null);
        unbinder = ButterKnife.bind(this, rootView);
        avatar.setOnClickListener(this);
        about.setOnClickListener(this);
        feedback.setOnClickListener(this);
        policy.setOnClickListener(this);
        business.setOnClickListener(this);
        fansContainer.setOnClickListener(this);
        followContainer.setOnClickListener(this);
        point.setOnClickListener(this);
        contact.setOnClickListener(this);
        share.setOnClickListener(this);
        data.setOnClickListener(this);
        moments.setOnClickListener(this);
        wiki.setOnClickListener(this);
        settings.setOnClickListener(this);
        profilePartner.setOnClickListener(this);
        dingyue.setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (InitManager.getInstance().getUser() != null) {
            presenter.getSelfInfo();
// TODO           presenter.getSubscribedTags();
        }
    }

    @Override
    public void initData() {
        //added since 3.0.1 检查合伙人『新』字是否显示过
        boolean flag = PrefUtil.getBoolean(AppConfig.PrefConfig.PREF_PROFILE_NEW);
        if(!flag){
            profilePartnerNew.setVisibility(View.VISIBLE);
        }

        try {
            contactValue.setText(ConfigParamsManager.getInstance().getServiceMobile());
            presenter = new ProfileFragmentPresenter(this, getActivity());
            if (InitManager.getInstance().getUser() == null) {
                profileNick.setText("登录/注册");
                profileSign.setText("");
            } else {
                bindUserInfo();
                presenter.getSelfInfo();

            }
        } catch (Exception e) {

        }
    }

    private void bindUserInfo() {
        if (InitManager.getInstance().getUser() != null) {
            settings.setVisibility(View.VISIBLE);
            String nick = StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().nickname) ? "未设置" : InitManager.getInstance().getUser().nickname;
            if (BuildConfig.LOG_DEBUG) {
                nick = nick + "[uid:" + InitManager.getInstance().getUserId() + "]";
            }
            profileNick.setText(nick);
            if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().avatar)) {
                avatar.setImageResource(R.drawable.icon_default_logo);
            } else {
                ImageLoader.getInstance().loadImageView(getActivity(),
                        InitManager.getInstance().getUser().avatar, avatar);
            }

            profileSign.setText(StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().sign) ? "这家伙很懒" : InitManager.getInstance().getUser().sign);
            pointValue.setText(InitManager.getInstance().getUser().userPoint + "");
            fansValue.setText(InitManager.getInstance().getUser().fansCount + "");
            followValue.setText(InitManager.getInstance().getUser().concernCount + "");
            if (InitManager.getInstance().getUser().untilNow <= 0) {
                InitManager.getInstance().getUser().untilNow = 1;
            }
            companyValue.setText(InitManager.getInstance().getUser().untilNow + "");
            bindProfileTags();
        } else {
            settings.setVisibility(View.GONE);
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.profile_fans:
            case R.id.profile_settings:
            case R.id.profile_follow:
            case R.id.profile_avatar:
            case R.id.profile_point:
            case R.id.profile_data:
            case R.id.profile_dingyue:
            case R.id.profile_moments:
                Log.d(TAG, "avatar clicked");
                if (InitManager.getInstance().getUser() != null) {
                    if (id == R.id.profile_avatar
                            || id == R.id.profile_settings) {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                            BindMobileActivity.startForResult(getActivity());
                            return;
                        }
                        ProfileEditActivity.startForResult(getActivity(), InitManager.getInstance().getUser());
                    } else if (id == R.id.profile_fans) {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                            BindMobileActivity.startForResult(getActivity());
                            return;
                        }
                        FollowFansActivity.start(getActivity(), false, InitManager.getInstance().getUserId());
                    } else if (id == R.id.profile_follow) {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                            BindMobileActivity.startForResult(getActivity());
                            return;
                        }
                        FollowFansActivity.start(getActivity(), true, InitManager.getInstance().getUserId());
                    } else if (id == R.id.profile_point) {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                            BindMobileActivity.startForResult(getActivity());
                            return;
                        }
                        PointRecordActivity.start(getActivity());
                    } else if (id == R.id.profile_data) {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                            BindMobileActivity.startForResult(getActivity());
                            return;
                        }
                        MyDataActivity.start(getActivity());
                    } else if (id == R.id.profile_moments) {
                        MyContentActivity.start(getActivity());
                    }else if (id == R.id.profile_dingyue) {
//                        DingyueActivity.start(getActivity());
                        new DingyueDialog().showDingyueDialog(getActivity());
                    }

                } else {
                    LoginActivity.startForResult(getActivity());
                }

                break;
            case R.id.profile_wiki:
                WebViewActivity.start(getActivity(), HttpConfig.WIKI_URL, "备孕百科","");
                break;
            case R.id.profile_about:
                AboutActivity.start(getActivity());
                break;
            case R.id.profile_feedback:
                FeedbackActivity.start(getActivity());
                break;
            case R.id.profile_contact:
                if (!StringUtil.isNullOrEmpty(ConfigParamsManager.getInstance().getServiceMobile())) {
                    SysUtil.contact(getActivity(), ConfigParamsManager.getInstance().getServiceMobile());
                }

                break;
            case R.id.profile_share:
                new BaseDialog().showShareDialog(getActivity(), new BaseDialog.OnShareItemSelected() {
                    @Override
                    public void onShareItemSelected(int item) {
                        String platName = "";
                        if (item == BaseDialog.OnShareItemSelected.TYPE_MOMENT) {
                            platName = WechatMoments.NAME;
                        } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN) {
                            platName = Wechat.NAME;
                        } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIBO) {
                            platName = SinaWeibo.NAME;
                        } else if (item == BaseDialog.OnShareItemSelected.TYPE_QQ) {
                            platName = QQ.NAME;
                        }
                        if (StringUtil.isNullOrEmpty(platName)) {
                            return;
                        }
                        ShareUtil.getInstance().shareApp(platName, new ShareUtil.IShareCallback() {
                            @Override
                            public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                                showToast(isSuccess ? "分享成功" : failReason);
                                if (isSuccess && InitManager.getInstance().getUser() != null) {
                                    TaskDBRecord record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), TimeUtil.getCurrentDate());
                                    record.shareAppCount++;
                                    if (record.shareAppCount > 1) {
                                        record.shareAppCount = 1;
                                    } else {
                                        presenter.sharePoint();
                                    }
                                    DBManager.getInstance().updateTaskRecord(record);
                                }
                            }
                        });
                    }
                });
                break;
            case R.id.profile_policy:
                WebViewActivity.start(getActivity(), HttpConfig.POLICYY_URL, "协议与隐私","");
                break;
            case R.id.profile_business:
                BusinessActivity.start(getActivity());
                break;
            case R.id.profile_partner:
                profilePartnerNew.setVisibility(View.GONE);
                PrefUtil.saveBoolean(AppConfig.PrefConfig.PREF_PROFILE_NEW,true);
                ((MainActivity) getActivity()).hideProfileNoti();
                WebViewActivity.start(getActivity(),HttpConfig.PARTNER_INTRO_URL,"合伙人","");
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == AppConfig.RequestResult.REQUEST_CODE_PROFILE_EDIT) {
            refreshFragmentData();
        }
    }

    @Override
    public void refreshFragmentData() {
        Log.d(TAG, "refreshFragmentData");
        initData();
    }

    @Override
    public void OnSelfInfoGet(User user) {
        InitManager.getInstance().getUser().joinExtraInfo(user);
        bindUserInfo();

    }

    @Override
    public void onGetInfoFailed(String reason) {
//        showToast(reason);
    }

    @Override
    public void onSharePointSuccess(String tips) {
        Log.d(TAG, "onSharePointSuccess");
        showToast(tips);
        bindUserInfo();
    }

    @Override
    public void onSubscribedTagsGet(boolean success, List<PTag> tags, String failReason) {
        bindProfileTags();
        if (getActivity() != null && !getActivity().isFinishing() && getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).checkTagSubscribeStatus();
        }
    }

    private synchronized void bindProfileTags() {
        profileTags.setOnClickListener(null);
        if (InitManager.getInstance().getTags() == null || InitManager.getInstance().getTags().isEmpty()) {
            profileTags.setText("选择标签获得更好的内容和圈子推荐");
            profileTags.setTextColor(Color.RED);
            profileTags.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TagSubscribeActivity.startForResult(getActivity());
                }
            });
        } else {
            List<PTag> tags = InitManager.getInstance().getTags();
            profileTags.setTextColor(Color.WHITE);
            profileTags.setText(getTagsDisplaySpannable(tags));
        }
    }

    private SpannableStringBuilder getTagsDisplaySpannable(List<PTag> tags) {
        int len = tags.size();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            sb.append(tags.get(i).name);
            sb.append(" ");
        }
        String orgStr = sb.toString();
        SpannableStringBuilder builder = new SpannableStringBuilder(orgStr);
        for (int i = 0; i < len; i++) {
            PTag tag = tags.get(i);
            int index = orgStr.indexOf(tag.name);
            int end = index + tag.name.length();
            BackgroundColorSpan bgSpan = new BackgroundColorSpan(ColorUtils.getRandomTagBgColor());
            builder.setSpan(bgSpan, index, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            ForegroundColorSpan bgSpan2 = new ForegroundColorSpan(Color.WHITE);
            builder.setSpan(bgSpan2, index, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }

}
